import json
import time

from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection

from AiJiaHome.utils.response_code import RET
from AiJiaHome.utils.views import LoginRequiredJSONMixin
from houses.models import House
from orders.models import Order


class AddOrderView(LoginRequiredJSONMixin, View):
    '''添加订单'''

    def post(self, request):
        '''添加订单'''
        # 请求参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 检验参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({"errno": RET.DATAERR, "errmsg": "缺少必传参数"})
        try:
            sd = time.strptime(start_date, "%Y-%m-%d")
            sd = int(time.mktime(sd))
            ed = time.strptime(end_date, "%Y-%m-%d")
            ed = int(time.mktime(ed))
            days = int(ed - sd)
            days = int(days / (3600 * 24))
            if days <= 0:
                return JsonResponse({"errno": RET.DATAERR, "errmsg": "日期错误"})
        except Exception:
            return JsonResponse({"errno": RET.DATAERR, "errmsg": "日期错误"})

        try:
            house = House.objects.get(id=house_id)
            # 房屋订单书加一
            house.order_count += 1
            # 　添加房屋订单
            order = Order.objects.create(
                user=request.user,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=house.price * days
            )
            house.save()
        except Exception:
            return JsonResponse({"errno": RET.DBERR, "errmsg": "请求数据库错误"})

        return JsonResponse({"data": {"order_id": order.id}, "errno": RET.OK, "errmsg": "OK"})

    def get(self, request):
        '''我的订单'''
        # 接收参数
        role = request.GET.get('role')
        # 判断和检验参数
        if role == 'custom':
            orders = Order.objects.filter(user=request.user).order_by('-create_time')
        elif role == 'landlord':
            if (request.user.real_name is not None) and (request.user.id_card is not None):
                houses = House.objects.filter(user=request.user)
                orders = Order.objects.filter(house__in=houses).order_by('-create_time')
            else:
                return JsonResponse({"errmsg": "未实名认证", "errno": RET.USERERR})
        else:
            return JsonResponse({"errmsg": "请求参数错误", "errno": RET.DATAERR})
        try:
            order_list = []
            for order in orders:
                order_list.append(
                    {
                        "amount": order.amount,
                        "comment": order.comment,
                        "ctime": str(order.create_time)[:10],
                        "days": order.days,
                        "end_date": str(order.end_date)[:10],
                        "img_url": order.house.index_image_url,
                        "order_id": order.id,
                        "start_date": str(order.begin_date)[:10],
                        "status": order.status,
                        "title": order.house.title
                    }
                )
        except Exception:
            return JsonResponse({"errno": RET.DBERR, "errmsg": "请求数据库错误"})

        return JsonResponse({"data": {"orders": order_list}, "errmsg": "OK", "errno": RET.OK})

    def put(self, request):
        '''接单/拒单'''
        # 接收参数
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        order_id = json_dict.get('order_id')
        reason = json_dict.get('reason')
        # 检验参数
        if not all([action, order_id]):
            return JsonResponse({"errno": RET.DATAERR, "errmsg": "缺少必传参数"})
        try:
            order = Order.objects.get(id=order_id)
            if action == 'accept':
                order.status = Order.ORDER_STATUS_CHOICES[3][0]
            elif action == 'reject':
                order.status = Order.ORDER_STATUS_CHOICES[6][0]
                order.comment = reason
            else:
                return JsonResponse({"errno": RET.DATAERR, "errmsg": "参数错误"})

            order.save()
        except Exception:
            return JsonResponse({"errno": RET.DBERR, "errmsg": "请求数据库错误"})

        return JsonResponse({"errno": RET.OK, "errmsg": "OK"})


class OrderCommentView(LoginRequiredJSONMixin, View):
    '''评价订单'''

    def put(self, request):
        '''评价订单'''

        # 接收参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        order_id = json_dict.get('order_id')

        # 校验参数
        if not all([comment, order_id]):
            return JsonResponse({"errno": RET.DATAERR, "errmsg": "缺少必传参数"})

        try:
            order = Order.objects.get(id=order_id)
            order.comment = comment
            order.status = Order.ORDER_STATUS_CHOICES[4][0]
            order.save()
        except:
            return JsonResponse({"errno": RET.DBERR, "errmsg": "评论失败"})
        # 返回参数
        return JsonResponse({"errno": RET.OK, "errmsg": "OK"})
